package com.doyens.gmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doyens.gmall.common.constant.RedisConst;
import com.doyens.gmall.common.util.HttpClientUtil;
import com.doyens.gmall.model.enums.OrderStatus;
import com.doyens.gmall.model.order.OrderDetail;
import com.doyens.gmall.model.order.OrderInfo;
import com.doyens.gmall.order.mapper.OrderDetailMapper;
import com.doyens.gmall.order.mapper.OrderInfoMapper;
import com.doyens.gmall.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderService {

    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${ware.url}")
    private String wareUrl;

    @Override
    public boolean save(OrderInfo orderInfo) {


        //重写ServiceImpl的save方法，我们在保存orderInfo对象的同时，还要保存orderDetail
        //手动设置下订单的时间，
        orderInfo.setCreateTime(new Timestamp(new Date().getTime()));
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 1);
        //手动设置过期时间(天+1)
        orderInfo.setExpireTime(calendar.getTime());
        //算总价格
        orderInfo.sumTotalAmount();
        //设置订单状态
        orderInfo.setOrderStatus(OrderStatus.UNPAID.name());
        //设置订单的进度状态
        orderInfo.setProcessStatus(OrderStatus.UNPAID.name());
        //userId在controller中设置的
        //保存订单到数据库
        this.baseMapper.insert(orderInfo);
        //保存这个订单对应的订单详情
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        orderDetailList.forEach(orderDetail -> {
            orderDetail.setOrderId(orderInfo.getId());
            orderDetailMapper.insert(orderDetail);
        });
        return true;

    }

    /**
     * 生产流水号
     *
     * @param userId
     * @return
     */
    @Override
    public String getTradeNo(String userId) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String tradeKey = RedisConst.USER_KEY_PREFIX + userId + RedisConst.TRADEKEY_SUFFIX;
        redisTemplate.opsForValue().set(tradeKey, uuid, RedisConst.SKUKEY_TIMEOUT, TimeUnit.SECONDS);
        return uuid;
    }

    @Override
    public boolean checkTradeCode(String tradeNo, String userId) {
        //判断是否是重复提交
        String tradeKey = RedisConst.USER_KEY_PREFIX + userId + RedisConst.TRADEKEY_SUFFIX;
        //通过userId获取redis中的流水号
        String tradeNo4Redis = (String) redisTemplate.opsForValue().get(tradeKey);
        return !(StringUtils.isEmpty(tradeNo4Redis) || !tradeNo4Redis.equals(tradeNo));
    }

    @Override
    public void deleteTradeNo(String userId) {
        String tradeKey = RedisConst.USER_KEY_PREFIX + userId + RedisConst.TRADEKEY_SUFFIX;
        redisTemplate.delete(tradeKey);
    }

    @Override
    public boolean checkStock(Long skuId, Integer skuNum) {
        //调用库存api，远程调用用不了，库存项目可能不是java，无法集成springcloud
        // http协议通信
        String url = wareUrl + "/hasStock?skuId=" + skuId + "&num=" + skuNum;
        log.info("url:"+url);
        String hasStock = HttpClientUtil.doGet(url);
        log.info("hasStock:"+hasStock);
        return "1".equals(hasStock);
    }
}
